import { readFileSync, writeFileSync } from 'node:fs';
import { dungeons } from './dist/dungeons.js';

const [sourcePath, foreverPath, itemPath, questPath] = process.argv.slice(2);
if (!questPath) throw new Error('Usage: node import-quest-items.mjs <Quests.lua> <forever_quests.json> <foreverItemDB.lua> <foreverQuestDB.lua>');

const lua = readFileSync(sourcePath, 'utf8');
const forever = JSON.parse(readFileSync(foreverPath, 'utf8')).quests;
const itemFile = readFileSync(itemPath, 'utf8');
const foreverQuestIds = new Set([...readFileSync(questPath, 'utf8').matchAll(/^\s*\[(\d+)\]\s*=\s*\{/gm)].map(([, id]) => +id));
const items = new Map();
for (const [, id, name, npc, object] of itemFile.matchAll(/^\s*\[(\d+)\]\s*=\s*\{('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"),\s*(nil|\{[^{}]*\}),\s*(nil|\{[^{}]*\})/gm)) {
  items.set(+id, { name: name.slice(1, -1).replace(/\\(['"\\])/g, '$1'), objectOnly: npc === 'nil' && object !== 'nil' });
}

const positions = line => Object.fromEntries([...line.matchAll(/\[(\d+)\]\s*=\s*\{([\d., \-]+)\}/g)]
  .map(([, floor, raw]) => [floor, raw.split(',').map(Number)]));
const sharedPositions = new Map();
const groups = new Map();
let group, quest, inGoals = false;
for (const line of lua.split(/\r?\n/)) {
  if (line.startsWith('DR.QuestData')) inGoals = true;
  if (!inGoals) {
    const shared = line.match(/^\t\[(\d+)\] = \{/);
    if (shared) sharedPositions.set(+shared[1], positions(line));
    continue;
  }
  const groupKey = line.match(/^\t(\w+) = \{/);
  if (groupKey) {
    group = new Map();
    groups.set(groupKey[1], group);
  }
  const header = line.match(/^\t\t\[(\d+)\] = \{ -- (.+)/);
  if (header) {
    quest = { id: +header[1], title: header[2], goals: [] };
    group.set(quest.id, quest);
  }
  const goal = line.match(/^\t\t\t\{ "(\w+)", (\d+), n = (\d+)/);
  if (!goal || !quest) continue;
  const [, kind, count, order] = goal;
  const id = Number(line.match(/\bid = (\d+)/)?.[1]) || undefined;
  const stopNames = line.match(/\bstops = \{([^}]+)\}/)?.[1] ?? '';
  const shared = Number(line.match(/\bpts = P\[(\d+)\]/)?.[1]);
  quest.goals.push({
    kind, count: +count, order: +order, id,
    stops: [...stopNames.matchAll(/"(?:\\.|[^"\\])*"/g)].map(([name]) => JSON.parse(name)),
    points: shared ? sharedPositions.get(shared) ?? {} : positions(line)
  });
}

for (const [, key, id, original, title] of lua.matchAll(/^Q\.(\w+)\[(\d+)\] = Q\.\w+\[(\d+)\] -- (.+)$/gm)) {
  const group = groups.get(key);
  const quest = group?.get(+original);
  if (quest) group.set(+id, { ...quest, id: +id, title: title.trim(), alias: +original });
}

const keys = {
  'hall-of-thanes': 'hallofthanes', 'ragefire-chasm': 'ragefire',
  'ruins-of-lordaeron': 'ruinsoflordaeron', 'the-deadmines': 'deadmines', 'wailing-caverns': 'wailingcaverns',
  'shadowfang-keep': 'shadowfang', 'blackfathom-deeps': 'blackfathom', 'excavation-site-wetlands': 'excavationsite',
  'the-stockade': 'stockade', 'city-of-dalaran': 'dalaran', 'razorfen-kraul': 'razorfenkraul',
  'scarlet-monastery-graveyard': 'sm_graveyard', 'scarlet-monastery-library': 'sm_library',
  'scarlet-monastery-armory': 'sm_armory', 'scarlet-monastery-cathedral': 'sm_cathedral',
  'the-drowned-city': 'drownedcity', 'razorfen-downs': 'razorfendowns', 'kroldok-stronghold': 'kroldok',
  'alcaz-prison': 'alcazprison', 'sunken-temple': 'sunkentemple', 'blackrock-depths': 'blackrockdepths',
  'blackmaw-hold': 'blackmawhold', 'lower-blackrock-spire': 'lowerblackrock',
  'upper-blackrock-spire': 'upperblackrock', 'dire-maul-east': 'diremaul_east',
  'dire-maul-west': 'diremaul_west', 'dire-maul-north': 'diremaul_north',
  'shapers-terrace': 'shapersterrace', 'stratholme-main-gate': 'stratholme', 'stratholme-service-gate': 'stratholme'
};

const output = {};
for (const dungeon of dungeons) {
  const key = keys[dungeon.slug] ?? dungeon.slug;
  const floors = new Set(dungeon.floors.map(floor => String(floor.id)));
  const stopNames = new Set(dungeon.routes.flatMap(route => route.stops.map(stop => stop.name)));
  output[dungeon.slug] = [...(groups.get(key)?.values() ?? [])].flatMap(quest => {
    const entry = forever[key]?.[quest.id];
    if (!entry && !foreverQuestIds.has(quest.id)) return [];
    const goals = quest.goals.map(goal => {
      const known = entry?.goals.find(item => item.kind === goal.kind && item.n === goal.order);
      const item = items.get(goal.id);
      const name = known?.what ?? item?.name;
      const points = Object.fromEntries(Object.entries(goal.points).filter(([floor]) => floors.has(floor)));
      return {
        kind: goal.kind, count: goal.count, name, itemId: goal.id, objectOnly: item?.objectOnly || undefined,
        stops: goal.stops.filter(stop => stopNames.has(stop)),
        points
      };
    });
    if (!goals.some(goal => goal.kind === 'item' && goal.name)) return [];
    if (key === 'stratholme' && !goals.some(goal => goal.stops.length || Object.keys(goal.points).length)) return [];
    return [{ id: quest.id, title: quest.title, classic: !entry, alias: quest.alias, goals }];
  }).sort((a, b) => a.title.localeCompare(b.title) || a.id - b.id);
}

// The underlying location dataset is GPL-3.0-only. Its source and notices ship
// separately with the atlas at quest-source.lua and quest-data-license.txt.
writeFileSync('dist/quest-items.json', JSON.stringify(output) + '\n');
